from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from .models import author,article
# Create your views here.
#判断为空
def luoji(n):
    return n is None or str(n).strip()==''
#创建作者
@api_view(['POST'])
def author_reg(request):
    data=JSONParser().parse(request)
    name=data['name']
    email=data['email']
    bio=data['bio']
    if luoji(name) or luoji(email) or luoji(bio):
        return JsonResponse({
            'error':'创建失败'
        },status=404)

    author(name=name,email=email,bio=bio).save()
    return JsonResponse({
        'msg':'创建成功',
        'name':name,
        'email':email,
        'bio':bio,
    },status=200)

#创建文章
@api_view(['POST'])
def article_reg(request):
    data=JSONParser().parse(request)
    title=data['title']
    content=data['content']
    author_id=data['author_id']
    if luoji(title) or luoji(content) or luoji(author_id):
        return JsonResponse({
            'error':'创建失败',
        },status=500)

    article(title=title,content=content,author_id_id=author_id).save()
    return JsonResponse({
        'msg':'文章创建成功',
        'title':title,
        'content':content,
        'author_id':author_id,
        'code':201
    })


#获取作者列表
@api_view(['GET'])
def liebiao(request):
    author_id=request.GET.get('author_id')
    if luoji(author_id):
        datas=author.objects.filter()
        lis=[]
        for data in datas:
            lis.append({
                'name':data.name,
                'email':data.email,
                'bio':data.bio,
            })
        return JsonResponse({
            'msg':'获取成功',
            'data':lis
        })
    if author.objects.filter(id=author_id).exists():
        datas = author.objects.filter(id=author_id)
        lis = []
        for data in datas:
            lis.append({
                'name':data.name,
                'email':data.email,
                'bio':data.bio,
            })
        return JsonResponse({
            'msg': '获取成功',
            'data': lis
        })
    if author.objects.filter(id=author_id).exists() is False:
        return JsonResponse({
            'msg': '没有查询到任何作者信息'
        })

#更新作者信息
@api_view(['PUT'])
def updata(request):
    data=JSONParser().parse(request)
    id=data.get('id')
    name=data.get('name')
    email=data.get('email')
    bio=data.get('bio')
    obj=author.objects.get(id=id)
    obj.name=name
    obj.email=email
    obj.bio=bio
    obj.save()
    return JsonResponse({
        'msg':'更新成功',
        'name':name,
        'email':email,
        'bio':bio,
    })

